<?php

namespace App\Console\Commands\Init;

use GuzzleHttp\Client;
use Illuminate\Console\Command;

class EsInit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @example php artisan init:es
     * @var string
     */
    protected $signature = 'es:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Init ElasticSearch';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //读取配置
        $host = config('scout.elasticsearch.hosts')[0];
        $template = config('scout.elasticsearch.template');
        $index = config('scout.elasticsearch.index');

        //创建template
        $client = new Client(['verify' => false]);
        $url = $host . '/_template/'. $template;

        //模板作用于要做用的索引
        $param = [
            'json' => [
                'index_patterns' => [$template."*"],
                'order' => 1,
                'settings' => [
                    'number_of_shards' => 1,
                    'number_of_replicas' => 1,
                ],
                'mappings' => [
                        'dynamic_templates' => [
                            [
                                'string' => [
                                    'match_mapping_type' => 'string',
                                    'mapping' => [
                                        'type' => 'text',
                                        'analyzer' => 'ik_smart', //用ik_smart进行解析（ik是专门解析中的插件）
                                        'fields' => [
                                            'keyword' => [
                                                'type' => 'keyword'
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]

                ]
            ]
        ];
        try {
            $result = $client->put($url, $param);
        } catch (\Exception $e) {
            $this->warn("[ERROR] : create template failed! " . $e->getCode() .' - '. $e->getMessage());
            return false;
        }
        if ($result) {
            $result = [
                'success' => $result->getReasonPhrase(),
                'code' => $result->getStatusCode(),
                'info' => $result->getBody()->getContents()
            ];
        }
        $this->info('============create template success============' .PHP_EOL.json_encode($result));

        //创建index
        $url = $host . '/' . $index;
        $param = [
            'json' => [
                'settings' => [
                    'refresh_interval' => '5s',
                    'number_of_shards' => 1,
                    'number_of_replicas' => 0,
                ],
                'mappings' => [
                    'dynamic' => false,
                    'properties' => [],
                ]
            ]
        ];
        try {
            $result = $client->put($url, $param);
        } catch (\Exception $e) {
            $this->warn("[ERROR] : create index failed! " . $e->getCode() .' - '. $e->getMessage());
            return false;
        }
        if ($result) {
            $result = [
                'success' => $result->getReasonPhrase(),
                'code' => $result->getStatusCode(),
                'info' => $result->getBody()->getContents()
            ];
        }
        $this->info('============create index success==============='.PHP_EOL.json_encode($result));

        return 0;
    }
}
